<template>
  <NavTop></NavTop>
  <div class="borrow-apply-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h2>图书借阅申请</h2>
          <p>请填写完整信息提交借阅申请</p>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 - 左中右布局 -->
    <div class="main-content">
      <!-- 左侧边栏 -->
      <div class="left-sidebar">
        <el-card class="tips-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <i class="el-icon-warning-outline"></i>
              <span>借阅须知</span>
            </div>
          </template>

          <div class="tips-content">
            <div class="tip-item">
              <i class="el-icon-circle-check"></i>
              <span>爱护图书，损坏需要赔偿</span>
            </div>
            <div class="tip-item">
              <i class="el-icon-circle-check"></i>
              <span>若还书日期显示为<b>“∞”</b>，请联系管理员（如果还能找到）。</span>
            </div>
            <div class="tip-item">
              <i class="el-icon-circle-check"></i>
              <span>可申请续借，但需在到期前操作</span>
            </div>
            <div class="tip-item">
              <i class="el-icon-circle-check"></i>
              <span>同一本书被连续借阅3次却无人归还？禁止点击<b>“续借”</b>。</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 中间主要表单区域 -->
      <div class="center-content">
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <i class="el-icon-edit-outline"></i>
              <span>申请信息</span>
            </div>
          </template>
          <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="120px"
              class="borrow-form"
              @submit.prevent
          >
            <!-- 书籍选择 -->
            <el-form-item label="书籍名称" prop="bookId" class="form-item-enhanced">
              <el-select
                  v-model="form.bookId "
                  filterable
                  remote
                  placeholder="输入书名、作者或ISBN进行搜索"
                  :remote-method="searchBooksMethod"
                  :loading="searchLoading"
                  @change="handleBookSelect"
                  class="book-select"
                  size="large"
                  clearable
              >
                <el-option
                    v-for="item in bookOptions"
                    :key="item.id"
                    :label="`${item.bookName} - ${item.author}`"
                    :value="item.id"
                >
                  <div class="book-option">
                    <div class="book-title">{{ item.bookName }}</div>
                    <div class="book-meta">
                      <span class="author">{{ item.author }}</span>
                      <span class="isbn">ISBN: {{ item.isbn }}</span>
                      <el-tag
                          :type="item.quantity > 0 ? 'success' : 'danger'"
                          size="small"
                          class="stock-tag"
                      >
                        {{ item.quantity > 0 ? `库存${item.quantity}` : '暂无库存' }}
                      </el-tag>
                    </div>
                  </div>
                </el-option>
              </el-select>
              <div class="field-tip">
                <i class="el-icon-info"></i>
                支持按书名、作者、ISBN搜索
              </div>
            </el-form-item>

            <!-- 日期选择区域 -->
            <div class="date-section">
              <el-form-item label="预计归还日期" prop="dueTime" class="form-item-enhanced">
                <el-date-picker
                    v-model="form.dueTime"
                    type="date"
                    placeholder="选择归还日期"

                    :picker-options="returnDateOptions"
                    size="large"
                    class="date-picker"
                />
                <div class="field-tip">
                  <i class="el-icon-time"></i>
                  建议借阅期限不超过30天
                </div>
              </el-form-item>
            </div>

            <!-- 借阅用途 -->
            <el-form-item label="借阅用途" prop="purpose" class="form-item-enhanced">
              <el-input
                  v-model="form.purpose"
                  type="textarea"
                  :rows="4"
                  placeholder="请详细说明借阅用途，如：学习研究、课程作业、个人兴趣等"
                  maxlength="200"
                  show-word-limit
                  size="large"
              />
            </el-form-item>

            <!-- 操作按钮 -->
            <el-form-item class="form-actions">
              <el-button
                  type="primary"
                  size="large"
                  @click="submitForm"
                  :loading="submitLoading"
                  class="submit-btn"
              >
                <i class="el-icon-check"></i>
                {{ submitLoading ? '提交中...' : '提交申请' }}
              </el-button>
              <el-button
                  size="large"
                  @click="resetForm"
                  class="reset-btn"
              >
                <i class="el-icon-refresh"></i>
                重置表单
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 书籍信息预览 -->
        <transition name="slide-fade">
          <el-card
              v-if="selectedBook"
              class="book-info-card"
              shadow="hover"
          >
            <template #header>
              <div class="card-header">
                <i class="el-icon-notebook-1"></i>
                <span>书籍详情</span>
              </div>
            </template>
            <div class="book-details">
              <div class="book-cover">
                <div class="cover-placeholder">
                  <i class="el-icon-reading"></i>
                </div>
              </div>

              <div class="book-content">
                <h3 class="book-title">{{ selectedBook.bookName }}</h3>

                <div class="info-grid">
                  <div class="info-item">
                    <label>作者</label>
                    <span>{{ selectedBook.author }}</span>
                  </div>
                  <div class="info-item">
                    <label>ISBN</label>
                    <span>{{ selectedBook.isbn }}</span>
                  </div>
                  <div class="info-item">
                    <label>出版社</label>
                    <span>{{ selectedBook.publisher }}</span>
                  </div>
                  <div class="info-item">
                    <label>库存状态</label>
                    <el-tag
                        :type="selectedBook.quantity > 0 ? 'success' : 'warning'"
                        size="small"
                    >
                      {{ selectedBook.quantity > 0 ? `可借阅 (${selectedBook.quantity}本)` : '暂无库存' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </transition>
      </div>

      <!-- 右侧边栏 -->
      <div class="right-sidebar">
        <el-card class="contact-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <i class="el-icon-phone-outline"></i>
              <span>联系我们</span>
            </div>
          </template>

          <div class="contact-info">
            <p><i class="el-icon-phone"></i> 服务热线：314-159-9265</p>
            <p><i class="el-icon-message"></i> 邮箱：library@ray.com</p>
            <p><i class="el-icon-time"></i> 服务时间：19:00-8:00</p>
          </div>
        </el-card>

        <el-card class="help-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <i class="el-icon-question"></i>
              <span>常见问题</span>
            </div>
          </template>

          <div class="help-content">
            <div class="help-item">
              <p class="question">Q: 如何申请续借？</p>
              <p class="answer">A: 在到期前3天内可申请续借</p>
            </div>
            <div class="help-item">
              <p class="question">Q: 电车难题：扳轨道救1人还是5人？</p>
              <p class="answer">A: 先救画</p>
            </div>
            <div class="help-item">
              <p class="question">Q: 给你10亿，但会有一只蜗牛永远追杀你，被碰到就会死，你愿意吗？</p>
              <p class="answer">A: 11111,真给吗</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import {getBooks} from "@/api/book";
import {BorrowBook} from "@/api/borrow";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import NavTop from "@/components/NavTop.vue";
// import { searchBooks, createBorrow } from '@/api/borrow'

// 修复后的完整 setup 函数
export default {
  name: 'BorrowApply',
  components: {NavTop},
  setup() {
    const formRef = ref(null)
    const submitLoading = ref(false)

    const userId = ref(0)
    const storeduserId = sessionStorage.getItem('userId');
    userId.value = storeduserId || 0
    const route = useRoute()

    console.log('路由参数:', route.query)

    // 表单数据
    const form = reactive({
      userId: userId.value,
      bookId: '',
      borrowTime: new Date(),
      dueTime: '',
      purpose: ''
    })

    // 数据
    const bookOptions = ref([])
    const searchLoading = ref(false)
    const selectedBook = ref(null)
    const mockBooks = ref([])

    // 初始搜索关键词
    const initialSearchQuery = ref('')

    onMounted(async () => {
      try {
        // 获取所有书籍数据
        mockBooks.value = await getBooks()
        console.log('获取到的书籍数据:', mockBooks.value)

        // 从路由参数获取搜索关键词
        const bookName = route.query.bookName || ''
        const bookId = route.query.bookId || ''

        console.log('路由参数 - bookName:', bookName, 'bookId:', bookId)

        if (bookName) {
          // 有书名搜索词，执行搜索
          initialSearchQuery.value = bookName
          await performSearch(bookName)

          // 如果还有具体的bookId，选中对应的书籍
          if (bookId) {
            const targetBook = bookOptions.value.find(book =>
                book.id.toString() === bookId.toString()
            )
            if (targetBook) {
              form.bookId = targetBook.id
              selectedBook.value = targetBook
              console.log('已选中书籍:', targetBook)
            }
          }
        } else if (bookId) {
          // 只有bookId，没有搜索词，直接查找并选中
          const targetBook = mockBooks.value.find(book =>
              book.id.toString() === bookId.toString()
          )
          if (targetBook) {
            // 将找到的书籍加入选项列表
            bookOptions.value = [targetBook]
            form.bookId = targetBook.id
            selectedBook.value = targetBook
            initialSearchQuery.value = targetBook.bookName
            console.log('直接选中书籍:', targetBook)
          }
        }
      } catch (error) {
        console.error('初始化失败:', error)
      }
    })

    // 执行搜索的辅助函数
    const performSearch = async (query) => {
      if (query && query.trim() !== '') {
        bookOptions.value = mockBooks.value.filter(book =>
            book.bookName.toLowerCase().includes(query.toLowerCase()) ||
            book.author.toLowerCase().includes(query.toLowerCase()) ||
            book.isbn.includes(query)
        )
        console.log('搜索结果:', bookOptions.value)
      }
    }

    // 校验规则
    const rules = reactive({
      bookId: [
        { required: true, message: '请选择要借阅的书籍', trigger: 'change' }
      ],
      dueTime: [
        { required: true, message: '请选择预计归还日期', trigger: 'change' },
        { validator: validateReturnDate, trigger: 'change' }
      ],
      purpose: [
        { required: true, message: '请输入借阅用途', trigger: 'blur' },
        { min: 5, message: '借阅用途至少需要5个字符', trigger: 'blur' }
      ]
    })

    // 自定义验证函数
    function validateReturnDate(rule, value, callback) {
      if (value) {
        const borrowDate = new Date()
        const returnDate = new Date(value)
        const diffTime = Math.abs(returnDate - borrowDate)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

        if (returnDate <= borrowDate) {
          callback(new Error('归还日期必须晚于借阅日期'))
        } else if (diffDays > 30) {
          callback(new Error('借阅期限不能超过30天'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    // 日期选择器配置
    const returnDateOptions = computed(() => {
      return {
        disabledDate: (time) => {
          const normalizeDate = (date) => {
            const d = new Date(date);
            return new Date(d.getFullYear(), d.getMonth(), d.getDate());
          };

          const today = normalizeDate(new Date());
          const selectedDate = normalizeDate(time);
          const maxDate = normalizeDate(new Date());
          maxDate.setDate(maxDate.getDate() + 30);

          return selectedDate < today || selectedDate > maxDate;
        }
      };
    });

    // 搜索书籍方法
    const searchBooksMethod = async query => {
      console.log('搜索关键词:', query)
      if (query && query.trim() !== '') {
        searchLoading.value = true
        try {
          // 如果 mockBooks 为空，重新获取
          if (mockBooks.value.length === 0) {
            mockBooks.value = await getBooks()
          }

          await performSearch(query)
        } catch (error) {
          console.error('搜索书籍失败:', error)
          ElMessage.error('搜索书籍失败，请稍后重试')
        } finally {
          searchLoading.value = false
        }
      } else {
        bookOptions.value = []
      }
    }

    // 处理书籍选择
    const handleBookSelect = bookId => {
      const book = bookOptions.value.find(item => item.id === bookId)
      selectedBook.value = book
      console.log('选中的书籍:', book)

      if (book && book.quantity === 0) {
        ElMessage.warning('该书籍暂无库存，请选择其他书籍或联系管理员')
      }
    }

    // 处理借阅日期变化
    const handleBorrowDateChange = () => {
      if (form.dueTime) {
        nextTick(() => {
          formRef.value?.validateField('dueTime')
        })
      }
    }

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()

        if (selectedBook.value?.quantity === 0) {
          ElMessage.error('所选书籍暂无库存，无法借阅')
          return
        }

        submitLoading.value = true
        console.log('提交的表单数据:', form)

        await BorrowBook(form)
        ElMessage.success('借阅申请提交成功！请等待审核通知')
        resetForm()

      } catch (error) {
        if (error !== false) {
          console.error('提交失败:', error)
          ElMessage.error('提交失败，请稍后重试')
        }
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      selectedBook.value = null
      bookOptions.value = []
      initialSearchQuery.value = ''
    }

    return {
      formRef,
      form,
      rules,
      bookOptions,
      searchLoading,
      selectedBook,
      submitLoading,
      returnDateOptions,
      initialSearchQuery,
      searchBooksMethod,
      handleBookSelect,
      handleBorrowDateChange,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.borrow-apply-container {
  min-height: 90vh;
  background: linear-gradient(135deg, #eddbff 0%, rgba(118, 232, 255, 0.83) 100%);
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
}

.icon-wrapper {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  backdrop-filter: blur(10px);
}

.icon-wrapper i {
  font-size: 28px;
}

.header-text h2 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 600;
}

.header-text p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

/* 左中右布局 */
.main-content {
  display: grid;
  grid-template-columns: 280px 1fr 280px;
  gap: 30px;
  max-width: 1600px;
  margin: 0 auto;
  align-items: start;
}

/* 左侧边栏 */
.left-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 中间主要内容区域 */
.center-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  min-width: 0; /* 防止内容溢出 */
}

/* 右侧边栏 */
.right-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-card, .book-info-card, .tips-card, .contact-card, .help-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.card-header i {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
}

.borrow-form {
  padding: 20px 0;
}

.form-item-enhanced {
  margin-bottom: 32px;
}

.form-item-enhanced .el-form-item__label {
  font-weight: 600;
  color: #303133;
}

.book-select {
  width: 100%;
}

.book-option {
  padding: 8px 0;
}

.book-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.book-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.stock-tag {
  margin-left: auto;
}

.field-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.field-tip i {
  margin-right: 4px;
}

.date-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.date-picker {
  width: 100%;
}

.form-actions {
  margin-top: 40px;
  text-align: center;
}

.submit-btn {
  width: 160px;
  height: 48px;
  margin-right: 16px;
  border-radius: 24px;
  font-weight: 600;
}

.reset-btn {
  width: 120px;
  height: 48px;
  border-radius: 24px;
}

.book-info-card {
  animation: slideInUp 0.5s ease;
}

.book-details {
  display: flex;
  gap: 20px;
}

.book-cover {
  width: 80px;
  flex-shrink: 0;
}

.cover-placeholder {
  width: 80px;
  height: 100px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.book-content {
  flex: 1;
}

.book-title {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.info-item span {
  color: #303133;
  font-size: 14px;
}

.tips-content {
  padding: 8px 0;
}

.tip-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}

.tip-item i {
  color: #67c23a;
  margin-right: 8px;
  font-size: 16px;
}

.contact-info {
  padding: 8px 0;
}

.contact-info p {
  margin: 0 0 12px 0;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.contact-info i {
  color: #409eff;
  margin-right: 8px;
  width: 16px;
}

/* 右侧边栏新增的帮助卡片样式 */
.help-content {
  padding: 8px 0;
}

.help-item {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.help-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.question {
  margin: 0 0 6px 0;
  font-size: 13px;
  font-weight: 600;
  color: #303133;
}

.answer {
  margin: 0;
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

/* 动画效果 */
.slide-fade-enter-active {
  transition: all 0.3s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

@keyframes slideInUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-content {
    grid-template-columns: 250px 1fr 250px;
    gap: 20px;
  }
}

@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .left-sidebar, .right-sidebar {
    order: 2;
  }

  .center-content {
    order: 1;
  }
}

@media (max-width: 768px) {
  .borrow-apply-container {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
  }

  .icon-wrapper {
    margin-right: 0;
    margin-bottom: 16px;
  }

  .header-text h2 {
    font-size: 24px;
  }

  .date-section {
    grid-template-columns: 1fr;
  }

  .book-details {
    flex-direction: column;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .form-actions {
    text-align: left;
  }

  .submit-btn, .reset-btn {
    width: 100%;
    margin: 8px 0;
  }
}
</style>